package org.magicbox.qjunTPO.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.magicbox.qjunTPO.common.lang.Result;
import org.magicbox.qjunTPO.entity.User;
import org.magicbox.qjunTPO.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 欢迎添加科技实践队粉丝群：690849711
 * @since 2021-11-12
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    PasswordEncoder pw;

    /**
     * 通过用户id获取用户基本信息
     * @param id
     * @return
     */
    @RequestMapping("/getById/{id}")
    public Result getById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        user.setNewReques(null);
        user.setNewColection(null);
        user.setNewSysMsg(null);
        user.setNewLike(null);
        user.setPassword(null);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            System.out.println(authentication.getName()) ;
        }
        return Result.success(user);
    }

    /**
     * 返回用当前户的信息
     */
    @RequestMapping("/getMe")
    public  Result getMe(){
        Integer uid;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            uid =new Integer(authentication.getName()) ;
            User byId = userService.getById(uid);
            byId.setLastDate(LocalDateTime.now());
            userService.updateById(byId);
            return Result.success(byId);
        }
        return Result.fail("失败了,请重新登录");
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @return 是否成功
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Result add(@Validated @RequestBody User user){
        LocalDateTime nowdate = LocalDateTime.now();
        Integer marker = 0;
        //如果填写了学号应当将其作为1学号注册用户
        if(user.getStuid()!=null){
            marker = 1;
        }
        user.setBirth(nowdate.toLocalDate());
        user.setNewSysMsg(nowdate);
        user.setMarker(marker);
        user.setPassword(pw.encode(user.getPassword()));
        try {
            userService.save(user);
//            userService.updateLastUp(user);  注册成功不应该就算是登录,所以本句注释掉
            return Result.success("应该是注册成功啦!");
        }catch (Exception e){
            return Result.fail(498,"有可能是失败了 先登陆看看!");
        }
    }


    /**
     * 查询手机号是否可用
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/exPhone/{phoneNumber}")
    public boolean exPhone(@PathVariable("phoneNumber")String phoneNumber){
        try {
           User user =  userService.getOne(new QueryWrapper<User>().eq("phone_number",phoneNumber));
           if(user.getId()==null) return true;
        }catch (Exception e){
            return true;
        }
        return false;
    }

    /**
     * 查询学号是否可用
     * @param sstuid
     * @return
     */
    @RequestMapping("/exStuid/{stuid}")
    public boolean exStuid(@PathVariable("stuid")String sstuid){
        if(sstuid.length()>10) return false;
        Integer stuid = new Integer(sstuid);
        try {
            User user =  userService.getOne(new QueryWrapper<User>().eq("stuid",stuid));
            if(user.getId()==null) return true;
        }catch (Exception e){
            return true;
        }
        return false;
    }

    /**
     * 设置新消息
     * @param uid
     */
    public void upNewRequest(Integer uid){
        User user = new User();
        user.setId(uid);
        user.setNewReques(1);
        userService.updateById(user);
    }

    @RequestMapping("/updateMyInfo")
    public Result updateMyInfo(@Validated @RequestBody User user){
        //获取当前用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Integer uid = new Integer(authentication.getName());
        User byId = userService.getById(uid);

        //当学号为空时才允许修改学号姓名
        if ((byId.getStuid() == null)&(user.getStuid()!=null)){
            byId.setName(user.getName());
            byId.setStuid(user.getStuid());
            byId.setMarker(1);
        }

        //修改用户信息
        byId.setNetname(user.getNetname());
        byId.setSex(user.getSex());

        //返回结果
        userService.updateById(byId);
        return Result.success(true);
    }
}

//
//    /**
//     * 通过手机号登录
//     * @param user 将用户数据传过来
//     * @return  返回登陆结果
//     */
//    @RequestMapping(value = "/lodingPhone",method = RequestMethod.POST)     //*
//    public Result  lodingPhone(@Validated @RequestBody User user){
//        User findUser ;
//        try {
//            findUser =userService.getOne(new QueryWrapper<User>().eq("phone_number", user.getPhoneNumber()));
//            Assert.notNull(findUser,"用户不存在");
//            findUser.setPassword("alskdfjalsf");
//        }catch (Exception e){
//            return Result.fail("登陆失败,请检查用户名密码");
//        }
//        if(!user.getPassword().equals(findUser.getPassword())){
//            return Result.fail(200,"密码错误");
//        }
//        userService.updateLastUp(findUser);
//        return Result.success(findUser);
//    }
//
//    /**
//     * 通过学号登录
//     * @param lodinguser
//     * @return
//     */
//    @RequestMapping(value = "/lodingStuid",method = RequestMethod.POST)     //*
//    public Result lodingId(@Validated @RequestBody User lodinguser){
//        try{
//            User user= userService.getOne(new QueryWrapper<User>().eq("stuid",lodinguser.getStuid()));
//            if(lodinguser.getPassword().equals(user.getPassword())){
//                user.setPassword("alskdfjalsf");
//
//                userService.updateLastUp(user);
//                return Result.success(user);
//            }else {
//                return Result.fail("登陆失败!");
//            }
//        }catch (Exception e){
//            return Result.fail("登录失败!");
//        }
//
//    }
